package utils

import (
	"errors"
	"time"

	"github.com/golang-jwt/jwt"
	"github.com/spf13/viper"
)

func CreateToken(userId int64, userName string) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256,
		jwt.MapClaims{
			"userId":   userId,
			"userName": userName,
			"exp":      time.Now().AddDate(0, 0, viper.GetInt("jwt.exp")).Unix(),
		})
	s, err := token.SignedString([]byte("libingyao"))
	return s, err
}

/*
解析token
@param tokenString string token字符串
@return user model.User 用户结构体
@return roles roleKey []string 角色key切片
@return []string permissions 权限切片
@return error 错误
*/
func ParseJWT(tokenString string) (int64, error) {
	if len(tokenString) > 7 && tokenString[:7] == "Bearer " {
		tokenString = tokenString[7:]
	}
	token, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
		if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
			return "", errors.New("校验失败")
		}
		return []byte("libingyao"), nil
	})

	if err != nil {
		err = errors.New("token无效")
		return 0, err
	}
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		userId, ok := claims["userId"].(float64)
		if !ok {
			return 0, errors.New("token无效")
		}
		return int64(userId), nil
	} else {
		err = errors.New("token无效")
		return 0, err
	}

}
